//
//  RHDeviceBatteryVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/12/5.
//

#import "RHDeviceBatteryVC.h"
#import "RHMasterItemCell.h"
#import "RHPackCell.h"
#import "RHDevPackModel.h"
#import "RHDevCellModel.h"
#import "RHDevEndPointDataModel.h"
#import "RHDevDataModel.h"

@interface RHDeviceBatteryVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
@property (nonatomic, strong) UICollectionView *master_collectView;

@property (nonatomic, strong) UICollectionView *pack_collectView;

@property (nonatomic, strong) QMUILabel *pageLab;

@property (nonatomic, assign) NSInteger ems_index;

@property (nonatomic, assign) NSInteger master_index;

@property (nonatomic, strong) QMUIButton *leftBtn;

@property (nonatomic, strong) QMUIButton *rightBtn;

//@property (nonatomic ,strong) NSArray *emsDataArr;

@property (nonatomic ,strong) NSArray *packDataArr;
@end

@implementation RHDeviceBatteryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"电池".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    [self getData];
    
}

-(void)getData{
    if (self.devModel.productTypeId == ProductType_HE_BAT||
        self.devModel.productTypeId == ProductType_HE_ALLINONE||
        self.devModel.productTypeId == ProductType_ME) {
        [self updateBuutonAndPageLab];
        [self getDevRelation];
    }else{
        [self updateBuutonAndPageLab];
    }
}

-(void)setupUI
{
    kWeakSelf;
    
    self.master_index = 0;
    
    UIView *topView = kView;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(5);
        make.height.mas_offset(30);
    }];
    
    __block UIView *lastView;
    NSArray *titles = @[@"正常电芯".rh_localized,@"高温电芯".rh_localized,@"低温电芯".rh_localized];
    NSArray *colors = @[@"#56C271",@"#FA8D15",@"#4787F0"];
    [titles enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *itemView = [self temperatureTagViewWithTitle:obj color:colors[idx]];
        [topView addSubview:itemView];
        if (lastView) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastView.mas_right).offset(10);
                make.top.bottom.mas_offset(0);
            }];
        }else{
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_offset(0);
                make.left.mas_offset(10);
            }];
        }
        lastView = itemView;
    }];
    
    
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _master_collectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    [_master_collectView registerClass:[RHMasterItemCell class] forCellWithReuseIdentifier:@"RHMasterItemCell"];
    _master_collectView.backgroundColor = CFTabViewBgColor;
    _master_collectView.layer.cornerRadius = 8;
    _master_collectView.layer.masksToBounds = YES;
    _master_collectView.showsVerticalScrollIndicator = NO;
    _master_collectView.showsHorizontalScrollIndicator = NO;
    _master_collectView.delegate = self;
    _master_collectView.dataSource = self;
    _master_collectView.pagingEnabled = YES;
    [self.view addSubview:_master_collectView];
    
    CGFloat w = kUI_WINDOW_W;
    //不展示
    [_master_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom);
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.height.offset(0);
       
    }];
    

    _pageLab = [[QMUILabel alloc]init];
    _pageLab.text = @"1/4";
    _pageLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.8];
    _pageLab.font = kSYSTEMFONT(15);
    _pageLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_pageLab];
    [_pageLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.bottom.equalTo(weakSelf.master_collectView).offset(-18);
    }];
    
    _leftBtn = [[QMUIButton alloc]init];
    [_leftBtn setImage:[UIImage imageNamed:@"scroll_left"] forState:UIControlStateNormal];
    [self.view addSubview:_leftBtn];
    [_leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(kScaleW(15));
        make.centerY.equalTo(weakSelf.master_collectView);
        make.width.height.offset(45);
    }];
    
    _rightBtn = [[QMUIButton alloc]init];
    [_rightBtn setImage:[UIImage imageNamed:@"scroll_right"] forState:UIControlStateNormal];
    [self.view addSubview:_rightBtn];
    [_rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(kScaleW(-15));
        make.centerY.equalTo(weakSelf.master_collectView);
        make.width.height.offset(45);
    }];
    
    [[_leftBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        if(weakSelf.master_index == 0)return;
        weakSelf.master_index --;
        [weakSelf ButtonAction];
    }];
    
    [[_rightBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        if(weakSelf.master_index == weakSelf.masterDataArr.count-1)return;
        weakSelf.master_index ++;
        [weakSelf ButtonAction];
    }];
    
    UICollectionViewFlowLayout *pack_layout = [[UICollectionViewFlowLayout alloc]init];
    pack_layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _pack_collectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:pack_layout];
    [_pack_collectView registerClass:[RHPackCell class] forCellWithReuseIdentifier:@"RHPackCell"];
    _pack_collectView.backgroundColor = CFTabViewBgColor;
    _pack_collectView.layer.cornerRadius = 8;
    _pack_collectView.layer.masksToBounds = YES;
    _pack_collectView.showsVerticalScrollIndicator = NO;
    _pack_collectView.showsHorizontalScrollIndicator = NO;
    _pack_collectView.delegate = self;
    _pack_collectView.dataSource = self;
    _pack_collectView.pagingEnabled = NO;
    [self.view addSubview:_pack_collectView];
    
    [_pack_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
        make.top.equalTo(weakSelf.master_collectView.mas_bottom);
    }];
    

}

-(UIView*)temperatureTagViewWithTitle:(NSString*)title color:(NSString*)color;
{
    UIView *itemView = kView;
    
    UIView *lowPoint = kView;
    lowPoint.backgroundColor = kCOLOR_HEX(color);
    lowPoint.layer.cornerRadius = 3;
    [itemView addSubview:lowPoint];
    [lowPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(6, 6)));
        make.left.mas_offset(0);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *lowLab = [QMUILabel labelWithText:title font:kSYSTEMFONT(12) textColor:kCOLOR_HEX_A(@"#3F4443", 0.6)];
    [itemView addSubview:lowLab];
    [lowLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lowPoint.mas_right).offset(8);
        make.centerY.equalTo(lowPoint);
        make.right.mas_offset(-3);
    }];
    return itemView;
}


#pragma mark ------- 1.获取端点关系
- (void)getDevRelation{
    [QMUITips showLoadingInView:self.view];
    [RHDevEndPointDataModel startGetWithCompletionAPIKey:H_getDevRelation argument:@{@"deviceId":self.devModel.deviceId} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200 && ![request.responseJSONObject[@"data"] isKindOfClass:[NSNull class]]){
                NSArray *arr = [NSArray yy_modelArrayWithClass:[RHDevEndPointDataModel class] json:request.responseJSONObject[@"data"][@"data"]];
                //筛选出EMS
                NSMutableArray *emsArr = [NSMutableArray array];
                NSMutableArray *master233Arr = [NSMutableArray array];
                [arr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    //有的最上层是EMU模块
                    if([obj.type isEqualToString:@"EMU"]){
                        [obj.nodes enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull obj2, NSUInteger idx, BOOL * _Nonnull stop) {
                            //从EMU筛选EMS
                            if([obj2.type isEqualToString:@"EMS"]){
                                [emsArr addObject:obj2];
                            }
                            //233的master是在EMU下
                            if([obj2.type isEqualToString:@"Master"]){
                                [master233Arr addObject:obj2];
                            }
                        }];
                        
                    }
                    if([obj.type isEqualToString:@"EMS"]){
                        [emsArr addObject:obj];
                    }
                }];
                
                RHDevEndPointDataModel *emsModel = [emsArr firstObject];
                //筛选出Master
                NSMutableArray *masterArr = [NSMutableArray array];
                [emsModel.nodes enumerateObjectsUsingBlock:^(RHDevEndPointDataModel*  _Nonnull masterModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([masterModel.type isEqualToString:@"Master"]||[masterModel.type isEqualToString:@"MASTER"]) {
                        [masterArr addObject:masterModel];
                    }
                }];
                if ([self.devModel.deviceTypeCode is233DeviceType]) {
                    masterArr = master233Arr;
                }
                self.masterDataArr = masterArr.copy;
                [self.master_collectView reloadData];
                [self updateBuutonAndPageLab];
            }else{
                //没有数据
                [self updateBuutonAndPageLab];
                [self.view addSubview: [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""]];
            }
            
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
    }];
}
#pragma mark -------2. 根据master获取 pack和电芯数据

-(void)getPackInfoWithMaster:(RHDevEndPointDataModel*)masterModel
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"masterSn":ValidNullData(masterModel.sn)};
    [RHDevPackModel startGetWithCompletionAPIKey:H_getPackCellData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
          
            self.packDataArr = resultModel.data;
            [self.packDataArr enumerateObjectsUsingBlock:^(RHDevPackModel  *_Nonnull packModel, NSUInteger idx, BOOL * _Nonnull stop) {
                NSMutableArray *cellArr = [NSMutableArray array];
                [packModel.volt enumerateObjectsUsingBlock:^(NSString*  _Nonnull volValue, NSUInteger idx, BOOL * _Nonnull stop) {
                    //电芯数据
                    RHDevCellModel *cellModel = [[RHDevCellModel alloc]init];
                    NSDecimalNumber *voltValue = [NSDecimalNumber decimalNumberWithDouble:[ValidNullData(volValue) doubleValue]];
                    cellModel.volt = [NSString stringWithFormat:@"%@",voltValue];
                      
                    if(idx<packModel.temp.count){
                        //两个电芯共用一个温度
                        NSInteger shareCount = idx/2;
                        if([self.devModel.deviceTypeCode is233DeviceType]){
                            shareCount = (idx+1)*19/51;//233的电芯温度是 以233的序号分布
                        }
                        if([self.devModel.deviceTypeCode isHVDeviceType]){
                            shareCount = idx/4;//高压的4个电芯共用一个温度
                        }
                        NSLog(@"---->下标取值:%ld",shareCount);
                        NSDecimalNumber *tempValue = [NSDecimalNumber decimalNumberWithDouble:[ValidNullData(packModel.temp[shareCount]) doubleValue]];
                        cellModel.temp = [NSString stringWithFormat:@"%@",tempValue];
                    }
                    [cellArr addObject:cellModel];
                }];
                packModel.cells = cellArr.copy;
            }];
            [self.pack_collectView reloadData];

        }else{
            self.packDataArr = @[];
            [self.pack_collectView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
        
}



#pragma mark ----- 上一页/下一页
-(void)ButtonAction
{
    CGFloat pageWidth = kUI_WINDOW_W-15-kRightOffset;
    [self.master_collectView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.master_index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    
    [self updateBuutonAndPageLab];
    [self.pack_collectView reloadData];
}


-(void)updateBuutonAndPageLab
{
    self.pageLab.text = [NSString stringWithFormat:@"%ld/%ld",self.master_index+1,self.masterDataArr.count];
    self.pageLab.hidden = self.masterDataArr.count<2;
    if(self.masterDataArr.count <= 1){
        self.leftBtn.hidden = YES;
        self.rightBtn.hidden = YES;
    }else{
        if(self.master_index == 0){
            self.leftBtn.hidden = YES;
            self.rightBtn.hidden = NO;
        }else
        if(self.master_index == self.masterDataArr.count - 1){
            self.leftBtn.hidden = NO;
            self.rightBtn.hidden = YES;
        }else{
            self.leftBtn.hidden = NO;
            self.rightBtn.hidden = NO;
        }
    }
   
    
    if(self.masterDataArr.count >0 && self.master_index >= 0){
        RHDevEndPointDataModel *masterModel = self.masterDataArr[self.master_index];
        [self getPackInfoWithMaster:masterModel];
//        [self.master_collectView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.offset(kUI_WINDOW_W*124/343.0);
//        }];
    }else{
        //有的设备没有主控
        [self getPackInfoWithMaster:[RHDevEndPointDataModel new]];
//        [self.master_collectView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.offset(0);
//        }];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if([scrollView isEqual:self.pack_collectView]){
        if(scrollView.isDragging){
            CGFloat pageWidth = kUI_WINDOW_W-10-kRightOffset;
            CGFloat x = scrollView.contentOffset.x + pageWidth*0.5;
//            self.index = x /pageWidth ;
//            [self updatePageLab];
            
//            NSLog(@"---->滚动下面 index = %ld",self.master_index);
//            NSLog(@"---->页面宽度 %f",pageWidth);
//            NSLog(@"---->滚动距离:%f",scrollView.contentOffset.x);
        }

    }else{
        if(scrollView.isDragging){
            CGFloat pageWidth = kUI_WINDOW_W;
            CGFloat x = scrollView.contentOffset.x + pageWidth*0.5;
            self.master_index = x /pageWidth ;
            [self updateBuutonAndPageLab];
//            NSLog(@"---->滚动上面index = %ld",self.index);
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    NSLog(@"--->手指已经松开,继续向前? %ld",decelerate);
    
    if([scrollView isEqual:self.pack_collectView]&&decelerate==NO){
        CGFloat pageWidth = kUI_WINDOW_W-10-kRightOffset;
        CGFloat x = scrollView.contentOffset.x + pageWidth*0.5;
        NSInteger scrollIndex = x /pageWidth ;
//        [self updatePageLab];
        [self adjustPackCollectionviewOffset:scrollIndex pageWidth:pageWidth];
        
    }else if([scrollView isEqual:self.master_collectView]&&decelerate==NO){
        CGFloat pageWidth = kUI_WINDOW_W;
        CGFloat x = scrollView.contentOffset.x + pageWidth*0.5;
        self.master_index = x /pageWidth ;
        [self updateBuutonAndPageLab];
        [self.pack_collectView reloadData];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"%s",__func__);
    if([scrollView isEqual:self.pack_collectView]){
        CGFloat pageWidth = kUI_WINDOW_W-10-kRightOffset;
        CGFloat x = scrollView.contentOffset.x + pageWidth*0.5;
        NSInteger scrollIndex = x /pageWidth ;
//        [self updatePageLab];
        [self adjustPackCollectionviewOffset:scrollIndex pageWidth:pageWidth];
    }else if([scrollView isEqual:self.master_collectView]){
        CGFloat pageWidth = kUI_WINDOW_W;
        CGFloat x = scrollView.contentOffset.x + pageWidth*0.5;
        self.master_index = x /pageWidth ;
        [self updateBuutonAndPageLab];
        [self.pack_collectView reloadData];
    }
}

-(void)adjustPackCollectionviewOffset:(NSInteger)scrollIndex pageWidth:(CGFloat)pageWidth
{
    CGFloat offset = (kRightOffset-10)/2;
    
    if(scrollIndex == 0){
        offset = 0;
    }else if(scrollIndex == self.packDataArr.count-1){
        offset = offset*2;
    }
    [self.pack_collectView setContentOffset:CGPointMake(pageWidth * scrollIndex -offset, 0) animated:YES];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if([collectionView isEqual:self.master_collectView]){
        return self.masterDataArr.count;
    }else{
        
        return self.packDataArr.count;
  
    }
    return 0;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if([collectionView isEqual:self.master_collectView]){
        RHMasterItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RHMasterItemCell" forIndexPath:indexPath];
        cell.layer.cornerRadius = 8;
        cell.layer.masksToBounds = YES;
        RHDevEndPointDataModel *masterModel = self.masterDataArr[indexPath.row];
        cell.masterModel = masterModel;
//        cell.masterLab.text = masterModel.endpoint;
        cell.masterLab.text = [NSString stringWithFormat:@"Master #%ld",indexPath.item+1];
        return  cell;
    }
    RHPackCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RHPackCell" forIndexPath:indexPath];
    RHDevPackModel *packModel = self.packDataArr[indexPath.item];
    cell.packModel = packModel;
    
    //233的电芯温度
    cell.packView.packTitleLab.text = [NSString stringWithFormat:@"Pack %ld#",indexPath.item+1];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if([collectionView isEqual:self.master_collectView]){
        CGFloat w = kUI_WINDOW_W;
        return CGSizeMake(w, w*124/343.0);
    }else{
        
        return CGSizeMake(kUI_WINDOW_W-kRightOffset-10, collectionView.height);
      
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if([collectionView isEqual:self.master_collectView]){
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return UIEdgeInsetsMake(0, 10, 0, 10);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if([collectionView isEqual:self.master_collectView]){
        return 0;
    }
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if([collectionView isEqual:self.master_collectView]){
        return 0;
    }
    return 10;
}

@end
